package com.easytodo.ui.today;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.androidnetworking.error.ANError;
import com.androidnetworking.interfaces.ParsedRequestListener;
import com.easytodo.ItemAdapter;
import com.easytodo.R;
import com.easytodo.Server;
import com.easytodo.entity.Item;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.logging.SimpleFormatter;

public class TodayFragment extends Fragment {

    ListView itemListView;
    private TodayModel todayModel;

    private void init(){
        itemListView=getActivity().findViewById(R.id.todayList);
        Log.v("MD",itemListView==null?"null":"not null");
        getTodayItem();
    }
    public void getTodayItem(){
        Fragment that=this;
        Server.getItemList(new ParsedRequestListener<List<Item>>() {
            @Override
            public void onResponse(List<Item> response) {
                Log.v("MD",response.toString());
                List<Item> todayItem=new ArrayList<>();
                for(Item item: response){
                    Date now=new Date();
                    Date itemDate=new Date(item.getDeathLine());
                    SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd");
                    String nowDay=formatter.format(now);
                    String itemDay=formatter.format(itemDate);

                    if(nowDay.equals(itemDay)&& !item.getImportance().equals("0"))
                        todayItem.add(item);
                }
                Collections.sort(todayItem);
                itemListView.setAdapter(new ItemAdapter(getActivity().getBaseContext(),todayItem,that,"today"));
            }

            @Override
            public void onError(ANError anError) {

            }
        });
    }

    @Override
    public void onStart() {
        super.onStart();
        init();
    }

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        todayModel =
                new ViewModelProvider(this).get(TodayModel.class);
        View root = inflater.inflate(R.layout.fragment_today, container, false);

        return root;
    }

}